#include "stdafx.h"
#include "CommandList.h"

CommandList commandList;

void displayUsage()
{
	wprintf(
		L"%s %s\n",
		L"RegTest", L"[-s script_file] [-?]"
		);
}

int processScript( const wchar_t* pScriptFile )
{
	wchar_t scriptLine[ MAX_PATH ];
	bool eof = false;
	FILE* fp = NULL;

	while ( !eof )
	{
		if ( pScriptFile )
		{
			if ( !fp )
			{
				_wfopen_s( &fp, pScriptFile, L"r" );
			}

			if ( !fp )
			{
				eof = true;
			}
			else
			{
				if ( fgetws( scriptLine, _countof(scriptLine), fp ) )
				{
					size_t iLastChar = wcslen( scriptLine ) - 1;
					if ( scriptLine[ iLastChar ] == L'\n' )
					{
						scriptLine[ iLastChar ] = L'\0';
					}

					wprintf( L"> %s\n", scriptLine );

					//	Do something with the line (and see if eof should be set)
					eof = commandList.Execute( scriptLine );
					wprintf( L"\n" );
				}
				else
				{
					eof = true;
				}
			}

			if ( eof && fp )
			{
				fclose( fp );
			}
		}
		else
		{
			wprintf( L"> " );
			if ( _getws_s( scriptLine ) )
			{
				//	Do something with the line (and see if eof should be set)
				eof = commandList.Execute( scriptLine );
				wprintf( L"\n" );
			}
		}
	}

	return ERROR_SUCCESS;
}

int wmain( int argc, wchar_t* argv[] )
{
	int status = ERROR_SUCCESS;
	if ( argc > 1 )
	{
		if ( !_wcsicmp( argv[1], L"-?" ) )
		{
			displayUsage();
		}
		else if ( !_wcsicmp( argv[1], L"-s" ) )
		{
			if ( argc <= 2 )
			{
				displayUsage();
			}
			else
			{
				status = processScript( argv[2] );
			}
		}
	}
	else
	{
		status = processScript( NULL );
	}

	return status;
}
